package com.mdd.controller;

import com.mdd.domain.Book;
import com.mdd.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("books")
public class BookController {

    @Autowired
    private BookService bookService;

    // 查询所有
    @GetMapping
    public R selectAll(){
//        int i = 1/0;
        List<Book> books = bookService.selectAll();
        Integer code = books != null ? Code.GET_OK:Code.GET_ERR;
        String msg = books != null ? "查询成功":"查询失败";
        return new R(code,msg,books);
    }

    // 添加图书
    @PostMapping()
    public R addBook(@RequestBody Book book){
        Boolean flag = bookService.addBook(book);
        Integer code = flag? Code.POST_ERR:Code.POST_ERR;
        String msg = flag ? "添加成功":"添加失败";
        return new R(code,msg);
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public R selectById(@PathVariable Integer id){
        Book book = bookService.selectById(id);
        Integer code = book != null ? Code.GET_OK:Code.GET_ERR;
        String msg = book != null ? "查询成功":"查询失败";
        return new R(code,msg,book);
    }

    // 根据ID修改
    @PutMapping()
    public R updateById(@RequestBody Book book){
        Boolean flag = bookService.updateById(book);
        Integer code = flag? Code.PUT_OK:Code.PUT_ERR;
        String msg = flag ? "修改成功":"修改失败";
        return new R(code,msg);
    }

    // 根据ID删除
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Integer id){
        Boolean flag = bookService.deleteById(id);
        Integer code = flag? Code.DELETE_OK:Code.DELETE_ERR;
        String msg = flag ? "删除成功":"删除失败";
        return new R(code,msg);
    }

}
